<template>
  <div class="container">
    <div class="container_left">
      <img src="../../assets/images/login_pic.png" alt="" />
    </div>
    <el-card style="width: 400px">
      <h1>智能组刀系统</h1>
      <el-form ref="form" :model="form" :rules="rules" label-width="70px">
        <el-form-item label="手机号" prop="mobilephone">
          <el-input v-model.trim="form.mobilephone" placeholder="请输入手机号码" size="small"></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="captcha">
          <el-input v-model.trim="form.captcha" size="small" placeholder="请输入手机验证码" maxlength="6">
            <template slot="append" v-if="captchaText"><span class="code_info1"> {{ times }}s后重新获取</span></template>
            <template slot="append" v-else><span class="code_info" @click="getCaptcha">获取验证码</span></template>
          </el-input>
        </el-form-item>
      </el-form>
      <el-button :loading="loading" type="primary" @click="onSubmit" size="small" style="width: 100%">登录</el-button>
      <div class="check">
        <el-checkbox v-model="checked"></el-checkbox>
        <p>我已阅读并同意<el-link type="primary" @click="getXieyi(1)">《服务条款》</el-link><el-link type="primary"
            @click="getXieyi(2)">《隐私政策》</el-link></p>
      </div>
      <div class="demo-image__preview">
        <div v-for="item in srcList" :key="item">
          <el-image style="width: 80px; height: 80px" :src="item" :preview-src-list="srcList">
          </el-image>
          <p style="font-size: 14px">{{ item == 'qrcodeImg' ? '放大小程序码' : '点击下载APP' }}</p>
        </div>
      </div>
    </el-card>
    <el-dialog :title="xieyiType == 1 ? '服务条款' : '隐私政策'" :visible.sync="dialogVisible" width="600px" top="2vh"
      style="max-height:90vh;padding-bottom:10vh">
      <div style="max-height:60vh; overflow-y: scroll;padding-bottom:10vh">
        <xieyi v-if="xieyiType == 1" />
        <xieyi1 v-else />
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapActions, mapGetters } from "vuex";
import { captchaApi, registApi } from "@/api/index.js";
import qrcodeImg from "@/assets/images/qrcode.jpg";
import appImg from "@/assets/images/app.jpg";
import { Message } from "element-ui";
const CryptoJS = require("crypto-js");
const Base64 = require("js-base64").Base64;
import xieyi from './xieyi.vue'
import xieyi1 from './xieyi1.vue'
export default {
  components: {
    xieyi,
    xieyi1
  },
  data () {
    var validatePhone = (rule, value, callback) => {
      let phoneGs = /^1\d{10}$/.test(value);
      if (!phoneGs) return callback(new Error("请输入正确的手机号"));
    };
    return {
      form: {
        mobilephone: "",
        captcha: "",
      },
      loading: false,
      qrcodeUrl: qrcodeImg,
      srcList: [qrcodeImg, appImg],
      isCountingDown: false, // 是否正在倒计时
      countdown: 60, // 倒计时秒数
      timer: null, // 定时器
      rules: {
        mobilephone: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" },
        ],
        captcha: [
          { required: true, message: "验证码不能为空", trigger: "blur" },
          { min: 6, max: 6, message: "验证码为6个字符", trigger: "blur" },
        ],
      },
      captchaText: "",
      times: 60,
      currentStatus: "",
      checked: false,
      dialogVisible: false,
      xieyiType: 1
    };
  },
  methods: {
    ...mapActions(["login"]), //第一个参数模块  第二个参数数组，模块下面的异步请求
    onSubmit () {
      // this.$refs.form.validate((valid) => {
      //   if (valid) {
      this.loading = true;
      if (this.currentStatus != "regist") {
        this.loginHandler();
      } else {
        this.registHandler();
      }

      //   }
      // })
    },
    //登录
    loginHandler () {
      this.login(this.form)
        .then((res) => {

          if (res.status && res.status == 'error') {
            Message.warning(res.message)
          } else {
            //登陆成功，跳转到首页
            this.$router.push("/");
          }
        })
        .finally(() => {
          this.loading = false;
        });
    },
    //注册
    registHandler () {
      registApi(this.form).then(res => {
        if (res.code == 200 && res.message == 'succ') {
          this.loginHandler()
        }
      })
    },

    //获取验证码
    getCaptcha () {
      if (this.form.mobilephone) {
        let regex = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
        if (!regex.test(this.form.mobilephone)) return Message.error("请输入正确格式的手机号")
        if (!this.checked) return Message.error("请阅读并同意协议")
        let _data = {
          mobilephone: this.form.mobilephone,
          postSecret: CryptoJS.MD5(
            "LXY" + (Number(this.form.mobilephone) + 1000) * 2
          ).toString(),
          type: "",
        };
        captchaApi(_data).then((res) => {
          if (res.code == 200 && !res.message.includes('失败')) {
            Message.success("短信验证码发送成功");
            this.captchaText = 1;
            this.timer = setInterval(() => {
              this.times--;
              if (this.times === 0) {
                this.captchaText = "";
                this.times = 60;
                clearInterval(this.timer);
              }
            }, 1000);
            if (
              res.code == 200 &&
              res.data &&
              res.data.mobilephone &&
              res.message == "用户不存在，请马上注册"
            ) {
              let curData = {
                mobilephone: this.form.mobilephone,
                postSecret: CryptoJS.MD5(
                  "LXY" + (Number(this.form.mobilephone) + 1000) * 2
                ).toString(),
                type: "regist",
              };
              captchaApi(curData).then((reg) => {
                if (reg.code == 200) {
                  this.currentStatus = "regist";
                }
              });
            }
          } else {
            Message.error(res.message);
          }
        });
      } else {
        Message.warning('请输入手机号')
      }
      // captchaApi
    },
    //查看协议
    getXieyi (type) {
      this.xieyiType = type
      this.dialogVisible = true
    }
  },
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  align-items: center;
  justify-content: space-around;
  height: 100vh;
  background: url("../../assets/images/login_bg.jpg") no-repeat 100%;
}

.container_left {
  width: 800px;

  img {
    width: 100%;
  }
}

h1 {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 20px;
  padding-top: 30px;
}

.code_info {
  cursor: pointer;
  color: #333;
}

.code_info1 {
  cursor: no-drop;
}

.demo-image__preview {
  margin: 40px auto;
  text-align: center;
  display: flex;
  justify-content: center;

  .el-image {
    margin-right: 0 !important;
  }

  div:first-child {
    margin-right: 50px;
    text-align: center;
  }
}

.check {
  display: flex;
  align-items: center;
  margin-top: 20px;

  p {
    margin-left: 10px;
    font-size: 14px;
    display: flex;
    align-items: center;
  }
}
</style>
